<?php
/**
 * 竞标控制器
 */

namespace app\api\controller;

use app\api\exception\ApiServiceException;
use app\api\service\ProjectLogService;
use app\common\model\Brand;
use app\common\model\Company;
use app\common\model\Project;
use app\common\model\ProjectLog;
use app\common\model\Spec;
use app\common\model\Tongji;
use app\common\model\Type;
use app\common\validate\ProjectLogValidate;
use hg\apidoc\annotation as Apidoc;
use think\response\Json;

/**
 * @Apidoc\Title("竞标")
 * @Apidoc\Group("index")
 */
class ProjectLogController extends ApiBaseController {
	protected array $loginExcept = [
		'api/project_log/list',
	];
	/**
	 * @Apidoc\Title("竞标记录")
	 * @Apidoc\Desc("竞标记录")
	 * @Apidoc\Method("GET")
	 * @Apidoc\Url("/api/project_log/index")
	 * @Apidoc\Returned("data",        type="array",                 desc="data")
	 */
	public function index(ProjectLogService $service): Json {
		try {
			$this->param['user_id'] = $this->uid;
			$data = $service->getList($this->param, $this->page, $this->limit);
			$result = [
				'project_log' => $data,
			];

			return api_success($result);
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}
	public function list(ProjectLogService $service): Json {
		try {
			$data = ProjectLog::with(['project', 'user'])->where('project_id', $this->param['project_id'])->select()->toArray();
			$result = [
				'project_log' => $data,
			];

			return api_success($result);
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}
	/**
	 * @Apidoc\Title("竞标")
	 * @Apidoc\Desc("竞标")
	 * @Apidoc\Method("POST")
	 * @Apidoc\Url("/api/project_log/add")
	 * @Apidoc\Param("project_id", type="string", desc="姓名"),
	 * @Apidoc\Param("detail", type="string", desc="竞标内容"),
	 * @Apidoc\Returned("data",        type="array",                 desc="data")
	 */
	public function add(ProjectLogValidate $validate, ProjectLogService $service): Json {
		$this->param['user_id'] = $this->uid;
		$this->param['status'] = 0;

		$this->param['detail'] = json_decode($this->param['detail'], true);

		$check = $validate->scene('api_add')->check($this->param);
		if (!$check) {
			return api_error($validate->getError());
		}
		$project = Project::where('id', $this->param['project_id'])->find();
		$company = Company::where('id', $this->user->company_id)->findOrEmpty();
		if ($company->isEmpty()) {
			return api_error('公司不存在');
		} elseif (!in_array($project['cate_id'], $company['cate'])) {
			return api_error('类目不符');
		}
		if ($project['status'] == 0) {
			return api_error('竞标未开始');
		}
		if (time() < strtotime($project['start_time'])) {
			return api_error('竞标未开始');
		}
		if ($project['status'] == 2) {
			return api_error('竞标已结束');
		}
		if (time() > strtotime($project['end_time'])) {
			return api_error('竞标已结束');
		}

		$project_log = ProjectLog::where('project_id', $this->param['project_id'])->where('user_id', $this->uid)->findOrEmpty();
		if (!$project_log->isEmpty()) {
			return api_error('只能竞标一次');
		}
		$money = 0;
		foreach ($this->param['detail'] as $key => $value) {
			if ($value['name'] != $project['detail'][$key]['name']) {
				return api_error('报价错误');
			}
			if ($value['money'] > $project['detail'][$key]['price'] && $project['detail'][$key]['price'] != 0) {
				return api_error('报价错误');
			}
			$money += $value['money'] * $value['num'];
			$type = Type::where('name', $value['name'])->find();
			$spec = Spec::where('name', $value['spec'])->find();
			$brand = Brand::where('name', $value['brand'])->find();
			$tongji = [
				'user_id' => $this->uid,
				'type_id' => $type->id ?? 0,
				'parent_id' => $type->parent_id ?? 0,
				'num' => $value['num'],
				'price' => $value['price'],
				'money' => $value['money'],
				'spec_id' => $spec->id ?? 0,
				'brand_id' => $brand->id ?? 0,
			];
			Tongji::create($tongji);
		}
		$this->param['all_money'] = round($money, 2);
		$result = $service->createData($this->param);
		Company::where('id', $this->user->company_id)->inc('open')->update();
		return $result ? api_success() : api_error();
	}
	public function searchsum($arr, $field) {
		if (!is_array($arr) || !$field) {
			return false;
		}

		$temp = array();
		foreach ($arr as $key => $val) {
			$temp[] = $val[$field];
		}

		return array_sum($temp);
	}
	/**
	 * 详情
	 * @param ProjectLogValidate $validate
	 * @param ProjectLogService $service
	 * @return Json
	 */
	public function info(ProjectLogValidate $validate, ProjectLogService $service): Json {
		$check = $validate->scene('api_info')->check($this->param);
		if (!$check) {
			return api_error($validate->getError());
		}

		try {

			$result = $service->getDataInfo($this->id);
			return api_success([
				'project_log' => $result,
			]);

		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

	/**
	 * 修改
	 * @param ProjectLogService $service
	 * @param ProjectLogValidate $validate
	 * @return Json
	 */
	public function edit(ProjectLogService $service, ProjectLogValidate $validate): Json {
		$project_log = ProjectLog::where('id', $this->id)->find();
		if ($project_log['xgcs'] > 1) {
			return api_error('只能修改一次');
		}
		$this->param['detail'] = json_decode($this->param['detail'], true);
		//print_r($this->param['detail']);
// 		$check = $validate->scene('api_edit')->check($this->param);
// 		if (!$check) {
// 			return api_error($validate->getError());
// 		}
		ProjectLog::where('id', $this->id)->inc('xgcs')->update();
		try {
			$service->updateData($this->id, $this->param);
			return api_success();
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

	/**
	 * 删除
	 * @param ProjectLogService $service
	 * @param ProjectLogValidate $validate
	 * @return Json
	 */
	public function del(ProjectLogService $service, ProjectLogValidate $validate): Json {
		$check = $validate->scene('api_del')->check($this->param);
		if (!$check) {
			return api_error($validate->getError());
		}

		try {
			$service->deleteData($this->id);
			return api_success();
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

}
